package pl.dalkia.services.scanner;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import pl.dalkia.services.scanner.services.fetcher.ConfigurationFileFetcher;
import pl.dalkia.services.scanner.services.fetcher.Fetchable;
import pl.dalkia.services.scanner.services.reader.LogFileReader;
import pl.dalkia.services.scanner.services.reader.Readable;
import pl.dalkia.services.scanner.services.writer.OutputFileWriter;
import pl.dalkia.services.scanner.services.writer.Writeable;

public class ScannerFactory {

	private static final Logger log = LoggerFactory
			.getLogger(ScannerFactory.class);

	public Scanner build(String[] args) {
		Fetchable fetcher = initializeFetcher(args);
		Readable reader = initializeReader(args);
		Writeable writer = initializeWriter(args);

		return new Scanner(fetcher, reader, writer);
	}
	
	
	private void exitApplication(int exitStatus){
		System.exit(exitStatus);
	}

	private Writeable initializeWriter(String[] args) {
		BufferedWriter outputFileBufferedWriter = null;
		try {
			outputFileBufferedWriter = new BufferedWriter(new FileWriter(
					args[2]));
		} catch (IOException e) {
			log.error(String.format("Unable to write to file provided at: %1$s.", args[2]));
			exitApplication(1);
		}
		Writeable writer = new OutputFileWriter(outputFileBufferedWriter);
		return writer;
	}

	
	private Readable initializeReader(String[] args) {
		BufferedReader logFileBufferedReader = null;
		try {
			logFileBufferedReader = new BufferedReader(new FileReader(args[1]));
		} catch (FileNotFoundException e) {
			log.error(String.format("No log file provided at: %1$s.", args[1]));
			exitApplication(1);
		}
		Readable reader = new LogFileReader(logFileBufferedReader);
		return reader;
	}

	
	private Fetchable initializeFetcher(String[] args) {
		BufferedReader configurationBufferedReader = null;
		try {
			configurationBufferedReader = new BufferedReader(new FileReader(
					args[0]));
		} catch (FileNotFoundException e) {
			log.error(String.format("No configuration file provided at: %1$s.", args[0]));
			exitApplication(1);
		}
		Fetchable fetcher = new ConfigurationFileFetcher(
				configurationBufferedReader);
		return fetcher;
	}
}
